package cn.jw.starter.redis.core.event;

import org.slf4j.MDC;

import com.alibaba.fastjson2.JSON;

import cn.jw.starter.redis.core.api.RedisApiService;
import cn.jw.starter.redis.core.event.model.AbstractRedisEvent;
import cn.jw.starter.redis.core.event.model.InnerRedisEventModel;
import jakarta.annotation.Resource;

/**
 * redis 订阅与发布的客户端，负责向redis发布消息
 *
 * @author: wds_prc
 * @since: 2024/8/2 16:49
 */
public class JwRedisPublishClient {

    public final static String COMMON_REDIS_EVENT_CHANNEL =
        "jingwei_common_redis_event_channel";
    @Resource
    private RedisApiService redisApiService;

    public void publishMsg(IRedisEventId redisEventId) {
        this.publishMsg(redisEventId, null);
    }

    /**
     * 向redis 频道发送事件内容
     *
     * @param event
     */
    public void publishMsg(IRedisEventId redisEventID,
        AbstractRedisEvent event) {
        if (redisEventID==null) {
            throw new IllegalArgumentException("redis event id 不能为空");
        }

        String value = null;
        if (event!=null) {
            value = JSON.toJSONString(event);
        }
        InnerRedisEventModel innerRedisEventModel = new InnerRedisEventModel();
        String tid = MDC.get("tid");
        innerRedisEventModel.setTid(tid);
        innerRedisEventModel.setEventData(value);
        String eventId = redisEventID.getEventId();
        innerRedisEventModel.setEventId(eventId);
        String eventData = JSON.toJSONString(innerRedisEventModel);
        redisApiService.convertAndSend(COMMON_REDIS_EVENT_CHANNEL, eventData);
    }
}
